// 飞书文档转公众号工具 - 主要功能实现

class LarkToMarkdown {
    constructor() {
        this.editor = document.getElementById('editor');
        this.preview = document.getElementById('preview');
        this.themeSelect = document.getElementById('themeSelect');
        this.mobilePreviewBtn = document.getElementById('mobilePreview');
        this.desktopPreviewBtn = document.getElementById('desktopPreview');
        this.copyBtn = document.getElementById('copyBtn');
        this.copyMarkdownBtn = document.getElementById('copyMarkdownBtn');
        this.copyPlainBtn = document.getElementById('copyPlainBtn');
        this.clearBtn = document.getElementById('clearBtn');
        this.pasteBtn = document.getElementById('pasteBtn');
        
        this.currentTheme = 'default';
        this.previewMode = 'mobile';
        
        this.init();
    }
    
    init() {
        // 配置marked选项
        marked.setOptions({
            highlight: function(code, lang) {
                if (lang && hljs.getLanguage(lang)) {
                    try {
                        return hljs.highlight(code, { language: lang }).value;
                    } catch (err) {}
                }
                return hljs.highlightAuto(code).value;
            },
            breaks: true,
            gfm: true
        });
        
        this.bindEvents();
        this.loadSampleContent();
        this.updatePreview();
    }
    
    bindEvents() {
        // 编辑器输入事件
        this.editor.addEventListener('input', () => {
            this.updatePreview();
        });
        
        // 主题切换
        this.themeSelect.addEventListener('change', (e) => {
            this.currentTheme = e.target.value;
            this.applyTheme();
        });
        
        // 预览模式切换
        this.mobilePreviewBtn.addEventListener('click', () => {
            this.setPreviewMode('mobile');
        });
        
        this.desktopPreviewBtn.addEventListener('click', () => {
            this.setPreviewMode('desktop');
        });
        
        // 复制功能
        this.copyBtn.addEventListener('click', () => {
            this.copyToClipboard();
        });
        
        this.copyMarkdownBtn.addEventListener('click', () => {
            this.copyMarkdown();
        });
        
        this.copyPlainBtn.addEventListener('click', () => {
            this.copyPlainText();
        });
        
        // 清空功能
        if (this.clearBtn) {
            this.clearBtn.addEventListener('click', () => {
                console.log('清空按钮被点击');
                this.clearEditor();
            });
        } else {
            console.error('清空按钮元素未找到');
        }
        
        // 粘贴功能
        this.pasteBtn.addEventListener('click', () => {
            this.pasteFromClipboard();
        });
        
        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey || e.metaKey) {
                switch(e.key) {
                    case 's':
                        e.preventDefault();
                        this.copyToClipboard();
                        break;
                    case 'm':
                        e.preventDefault();
                        this.copyMarkdown();
                        break;
                    case 'p':
                        e.preventDefault();
                        this.copyPlainText();
                        break;
                    case 'k':
                        e.preventDefault();
                        this.clearEditor();
                        break;
                }
            }
        });
    }
    
    loadSampleContent() {
        const sampleContent = `# 🚀 飞书文档转公众号排版工具

这是一个强大的**飞书文档转换工具**，可以帮助你快速将飞书文档转换为美观的公众号文章。

## 🌈 核心功能

| 功能 | 描述 | 支持情况 |
|:--|:--|:--:|
| 一键转换 | 从飞书文档直接复制，自动转换为 Markdown | ✓ |
| 实时预览 | 支持手机和电脑两种预览模式 | ✓ |
| 多种主题 | 提供默认、暖色、极简三种主题 | ✓ |
| 完整样式 | 支持图片、表格、代码等富文本格式 | ✓ |

## 📝 使用方法

1. 打开飞书文档，复制需要转换的内容
2. 粘贴到左侧编辑区
3. 右侧实时预览效果
4. 点击复制按钮，粘贴到公众号

## 🎨 支持的样式

### 文本格式化
- **重点内容**使用粗体
- *需要强调*使用斜体
- \`重要代码\`使用行内代码
- ~~已废弃内容~~使用删除线

### 代码展示

\`\`\`javascript
// 支持代码高亮
function formatDocument(content) {
  return markdown.format(content);
}
\`\`\`

### 引用示例

> 💡 小贴士：可以使用快捷键 \`Ctrl+S\` (Windows) 或 \`Command+S\` (Mac) 直接复制转换后的内容。

### 列表功能

#### 无序列表
- 支持基础列表
  - 支持多级列表
  - 自动缩进对齐
- 保持飞书格式

#### 有序列表
1. 第一步：复制飞书内容
2. 第二步：粘贴到编辑器
   1. 自动转换格式
   2. 实时预览效果
3. 第三步：复制到公众号

---

**开始使用：** 清空这些示例内容，粘贴你的飞书文档内容即可！`;
        
        this.editor.value = sampleContent;
    }
    
    updatePreview() {
        const markdownContent = this.editor.value;
        const htmlContent = this.convertMarkdownToHtml(markdownContent);
        this.preview.innerHTML = htmlContent;
        this.applyTheme();
        
        // 重新高亮代码
        this.preview.querySelectorAll('pre code').forEach((block) => {
            hljs.highlightElement(block);
        });
    }
    
    convertMarkdownToHtml(markdown) {
        // 预处理飞书特殊格式
        let processedMarkdown = this.preprocessLarkContent(markdown);
        
        // 转换为HTML
        let html = marked.parse(processedMarkdown);
        
        // 后处理HTML
        html = this.postprocessHtml(html);
        
        return html;
    }
    
    preprocessLarkContent(content) {
        // 处理飞书文档的特殊格式
        let processed = content;
        
        // 处理表格格式
        processed = this.processLarkTables(processed);
        
        // 处理列表格式
        processed = this.processLarkLists(processed);
        
        // 处理引用格式
        processed = this.processLarkQuotes(processed);
        
        // 处理代码块
        processed = this.processLarkCodeBlocks(processed);
        
        return processed;
    }
    
    processLarkTables(content) {
        // 简单的表格格式处理
        return content.replace(/\|\s*([^|]+)\s*\|/g, (match, cell) => {
            return `| ${cell.trim()} |`;
        });
    }
    
    processLarkLists(content) {
        // 处理列表项的缩进
        const lines = content.split('\n');
        const processedLines = lines.map(line => {
            // 处理无序列表
            if (line.match(/^\s*[•·-]\s+/)) {
                const indent = line.match(/^\s*/)[0].length;
                const content = line.replace(/^\s*[•·-]\s+/, '');
                const level = Math.floor(indent / 2);
                return '  '.repeat(level) + '- ' + content;
            }
            // 处理有序列表
            if (line.match(/^\s*\d+[.).]\s+/)) {
                const indent = line.match(/^\s*/)[0].length;
                const content = line.replace(/^\s*\d+[.).]\s+/, '');
                const level = Math.floor(indent / 2);
                return '  '.repeat(level) + '1. ' + content;
            }
            return line;
        });
        return processedLines.join('\n');
    }
    
    processLarkQuotes(content) {
        // 处理引用格式
        return content.replace(/^\s*[""]/gm, '> ');
    }
    
    processLarkCodeBlocks(content) {
        // 处理代码块格式
        return content.replace(/```([\s\S]*?)```/g, (match, code) => {
            const lines = code.split('\n');
            const firstLine = lines[0].trim();
            const language = firstLine.match(/^\w+$/) ? firstLine : '';
            const codeContent = language ? lines.slice(1).join('\n') : code;
            return `\`\`\`${language}\n${codeContent}\n\`\`\``;
        });
    }
    
    postprocessHtml(html) {
        // 添加公众号友好的样式
        let processed = html;
        
        // 为表格添加样式类
        processed = processed.replace(/<table>/g, '<table class="wechat-table">');
        
        // 为代码块添加样式类
        processed = processed.replace(/<pre><code/g, '<pre class="wechat-code"><code');
        
        // 为引用添加样式类
        processed = processed.replace(/<blockquote>/g, '<blockquote class="wechat-quote">');
        
        return processed;
    }
    
    applyTheme() {
        // 移除所有主题类
        const allThemes = ['theme-default', 'theme-warm', 'theme-minimal', 'theme-elegant', 'theme-ocean', 'theme-forest', 'theme-sunset', 'theme-lavender', 'theme-cherry', 'theme-mint'];
        
        // 从预览区域移除所有主题类
        this.preview.classList.remove(...allThemes);
        
        // 从body移除所有主题类
        document.body.classList.remove(...allThemes);
        
        // 添加当前主题类到预览区域和body
        const currentThemeClass = `theme-${this.currentTheme}`;
        this.preview.classList.add(currentThemeClass);
        document.body.classList.add(currentThemeClass);
    }
    
    setPreviewMode(mode) {
        this.previewMode = mode;
        
        // 更新按钮状态
        this.mobilePreviewBtn.classList.toggle('active', mode === 'mobile');
        this.desktopPreviewBtn.classList.toggle('active', mode === 'desktop');
        
        // 更新预览容器类
        this.preview.classList.toggle('mobile-preview', mode === 'mobile');
        this.preview.classList.toggle('desktop-preview', mode === 'desktop');
    }
    
    async copyToClipboard() {
        try {
            // 使用现代 Clipboard API
            if (navigator.clipboard && navigator.clipboard.write) {
                await this.copyWithClipboardAPI();
            } else {
                // 降级到传统方法
                await this.copyWithLegacyMethod();
            }
        } catch (error) {
            console.error('复制失败:', error);
            this.showMessage('❌ 复制失败，请手动选择内容复制', 'error');
        }
    }
    
    async copyWithClipboardAPI() {
        const htmlContent = this.generateWechatHtml();
        const plainText = this.generatePlainText();
        
        const clipboardItem = new ClipboardItem({
            'text/html': new Blob([htmlContent], { type: 'text/html' }),
            'text/plain': new Blob([plainText], { type: 'text/plain' })
        });
        
        await navigator.clipboard.write([clipboardItem]);
        this.showMessage('✅ 已复制富文本格式！可直接粘贴到公众号编辑器', 'success');
    }
    
    async copyWithLegacyMethod() {
        const htmlContent = this.generateWechatHtml();
        
        // 创建临时元素用于复制
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = htmlContent;
        tempDiv.style.position = 'absolute';
        tempDiv.style.left = '-9999px';
        tempDiv.style.top = '-9999px';
        tempDiv.style.opacity = '0';
        document.body.appendChild(tempDiv);
        
        try {
            // 选择内容
            const range = document.createRange();
            range.selectNodeContents(tempDiv);
            const selection = window.getSelection();
            selection.removeAllRanges();
            selection.addRange(range);
            
            // 复制到剪贴板
            const success = document.execCommand('copy');
            
            if (success) {
                this.showMessage('✅ 已复制到剪贴板！可以直接粘贴到公众号编辑器', 'success');
            } else {
                throw new Error('复制失败');
            }
        } finally {
            // 清理
            document.body.removeChild(tempDiv);
            window.getSelection().removeAllRanges();
        }
    }
    
    generateWechatHtml() {
        const previewContent = this.preview.innerHTML;
        
        // 处理HTML内容，添加内联样式
        let processedHtml = this.addInlineStyles(previewContent);
        
        // 生成适合公众号的HTML
        const wechatHtml = `<section style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif; line-height: 1.8; color: #333; word-wrap: break-word; word-break: break-all; margin: 0; padding: 0;">${processedHtml}</section>`;
        
        return wechatHtml;
    }
    
    generatePlainText() {
        // 生成纯文本版本
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = this.preview.innerHTML;
        return tempDiv.textContent || tempDiv.innerText || '';
    }
    
    addInlineStyles(html) {
        // 创建临时DOM来处理样式
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = html;
        
        // 设置容器基础字体大小和行高
        tempDiv.style.cssText += 'font-size: 16px; line-height: 1.75; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Helvetica Neue", Arial, sans-serif;';
        
        // 获取当前主题的配色方案
        const themeColors = this.getThemeColors();
        
        // 为不同元素添加内联样式
        this.styleHeaders(tempDiv, themeColors);
        this.styleParagraphs(tempDiv, themeColors);
        this.styleStrong(tempDiv, themeColors);
        this.styleEmphasis(tempDiv, themeColors);
        this.styleCode(tempDiv, themeColors);
        this.styleCodeBlocks(tempDiv, themeColors);
        this.styleBlockquotes(tempDiv, themeColors);
        this.styleLists(tempDiv, themeColors);
        this.styleTables(tempDiv, themeColors);
        this.styleLinks(tempDiv, themeColors);
        
        return tempDiv.innerHTML;
    }
    
    getThemeColors() {
        const themeColorMap = {
            'default': {
                primary: '#667eea',
                secondary: '#764ba2',
                text: '#333',
                strong: '#e74c3c',
                emphasis: '#8e44ad',
                code: '#e74c3c',
                codeBg: '#f8f9fa',
                blockquoteBorder: '#667eea',
                blockquoteBg: '#f8f9fa',
                blockquoteText: '#666'
            },
            'warm': {
                primary: '#d2691e',
                secondary: '#cd853f',
                text: '#5d4e37',
                strong: '#b8860b',
                emphasis: '#a0522d',
                code: '#b8860b',
                codeBg: '#faf0e6',
                blockquoteBorder: '#d2691e',
                blockquoteBg: '#faf0e6',
                blockquoteText: '#8b4513'
            },
            'minimal': {
                primary: '#6c757d',
                secondary: '#495057',
                text: '#2c3e50',
                strong: '#495057',
                emphasis: '#6c757d',
                code: '#495057',
                codeBg: '#f8f9fa',
                blockquoteBorder: '#6c757d',
                blockquoteBg: '#f8f9fa',
                blockquoteText: '#6c757d'
            },
            'elegant': {
                primary: '#d63384',
                secondary: '#e91e63',
                text: '#5d4e75',
                strong: '#d63384',
                emphasis: '#e91e63',
                code: '#721c24',
                codeBg: '#f8d7da',
                blockquoteBorder: '#f8d7da',
                blockquoteBg: 'rgba(248, 215, 218, 0.2)',
                blockquoteText: '#721c24'
            },
            'ocean': {
                primary: '#0369a1',
                secondary: '#0ea5e9',
                text: '#1e3a8a',
                strong: '#0369a1',
                emphasis: '#0ea5e9',
                code: '#0c4a6e',
                codeBg: '#bae6fd',
                blockquoteBorder: '#0ea5e9',
                blockquoteBg: 'rgba(14, 165, 233, 0.1)',
                blockquoteText: '#0c4a6e'
            },
            'forest': {
                primary: '#16a34a',
                secondary: '#22c55e',
                text: '#14532d',
                strong: '#16a34a',
                emphasis: '#22c55e',
                code: '#15803d',
                codeBg: '#bbf7d0',
                blockquoteBorder: '#22c55e',
                blockquoteBg: 'rgba(34, 197, 94, 0.1)',
                blockquoteText: '#15803d'
            },
            'sunset': {
                primary: '#ea580c',
                secondary: '#f97316',
                text: '#9a3412',
                strong: '#ea580c',
                emphasis: '#f97316',
                code: '#c2410c',
                codeBg: '#fed7aa',
                blockquoteBorder: '#f97316',
                blockquoteBg: 'rgba(249, 115, 22, 0.1)',
                blockquoteText: '#c2410c'
            },
            'lavender': {
                primary: '#9333ea',
                secondary: '#a855f7',
                text: '#581c87',
                strong: '#9333ea',
                emphasis: '#a855f7',
                code: '#6b21a8',
                codeBg: '#e9d5ff',
                blockquoteBorder: '#a855f7',
                blockquoteBg: 'rgba(168, 85, 247, 0.1)',
                blockquoteText: '#6b21a8'
            },
            'cherry': {
                primary: '#ec4899',
                secondary: '#f472b6',
                text: '#be185d',
                strong: '#ec4899',
                emphasis: '#f472b6',
                code: '#be185d',
                codeBg: '#fce7f3',
                blockquoteBorder: '#f472b6',
                blockquoteBg: 'rgba(244, 114, 182, 0.1)',
                blockquoteText: '#be185d'
            },
            'mint': {
                primary: '#059669',
                secondary: '#10b981',
                text: '#064e3b',
                strong: '#059669',
                emphasis: '#10b981',
                code: '#047857',
                codeBg: '#ccfbf1',
                blockquoteBorder: '#10b981',
                blockquoteBg: 'rgba(16, 185, 129, 0.1)',
                blockquoteText: '#047857'
            }
        };
        
        return themeColorMap[this.currentTheme] || themeColorMap['default'];
    }
    
    styleHeaders(container, themeColors) {
        const headers = container.querySelectorAll('h1, h2, h3, h4, h5, h6');
        headers.forEach(header => {
            const level = parseInt(header.tagName.charAt(1));
            let fontSize, marginTop, marginBottom, color;
            
            switch(level) {
                case 1:
                    fontSize = '28px'; // 1.75rem，主标题
                    color = themeColors.text;
                    marginTop = '1.5em';
                    marginBottom = '0.8em';
                    header.style.borderBottom = `2px solid ${themeColors.primary}`;
                    header.style.paddingBottom = '0.3em';
                    break;
                case 2:
                    fontSize = '24px'; // 1.5rem，二级标题
                    color = themeColors.primary;
                    marginTop = '1.3em';
                    marginBottom = '0.7em';
                    break;
                case 3:
                    fontSize = '20px'; // 1.25rem，三级标题
                    color = themeColors.secondary;
                    marginTop = '1.2em';
                    marginBottom = '0.6em';
                    break;
                case 4:
                    fontSize = '18px'; // 1.125rem，四级标题
                    color = themeColors.text;
                    marginTop = '1em';
                    marginBottom = '0.5em';
                    break;
                default:
                    fontSize = '16px'; // 1rem，五六级标题
                    color = themeColors.text;
                    marginTop = '1em';
                    marginBottom = '0.5em';
            }
            
            header.style.cssText += `font-size: ${fontSize}; color: ${color}; margin-top: ${marginTop}; margin-bottom: ${marginBottom}; font-weight: 600; line-height: 1.4;`;
        });
    }
    
    styleParagraphs(container, themeColors) {
        const paragraphs = container.querySelectorAll('p');
        paragraphs.forEach(p => {
            p.style.cssText += `margin: 1em 0; text-align: justify; line-height: 1.75; font-size: 16px; color: ${themeColors.text};`;
        });
    }
    
    styleStrong(container, themeColors) {
        const strongs = container.querySelectorAll('strong');
        strongs.forEach(strong => {
            strong.style.cssText += `color: ${themeColors.strong}; font-weight: 600;`;
        });
    }
    
    styleEmphasis(container, themeColors) {
        const ems = container.querySelectorAll('em');
        ems.forEach(em => {
            em.style.cssText += `color: ${themeColors.emphasis}; font-style: italic;`;
        });
    }
    
    styleCode(container, themeColors) {
        const codes = container.querySelectorAll('code:not(pre code)');
        codes.forEach(code => {
            code.style.cssText += `background: ${themeColors.codeBg}; padding: 2px 6px; border-radius: 4px; font-family: "Monaco", "Menlo", "Ubuntu Mono", monospace; font-size: 14px; color: ${themeColors.code}; border: 1px solid #e9ecef;`;
        });
    }
    
    styleCodeBlocks(container, themeColors) {
        const preBlocks = container.querySelectorAll('pre');
        preBlocks.forEach(pre => {
            pre.style.cssText += `background: ${themeColors.codeBg}; padding: 15px; border-radius: 8px; overflow-x: auto; margin: 1em 0; border-left: 4px solid ${themeColors.primary}; font-family: "Monaco", "Menlo", "Ubuntu Mono", monospace; line-height: 1.5;`;
            
            const code = pre.querySelector('code');
            if (code) {
                code.style.cssText += `background: none; padding: 0; color: ${themeColors.code}; border: none;`;
            }
        });
    }
    
    styleBlockquotes(container, themeColors) {
        const blockquotes = container.querySelectorAll('blockquote');
        blockquotes.forEach(blockquote => {
            blockquote.style.cssText += `border-left: 4px solid ${themeColors.blockquoteBorder}; padding: 15px; margin: 1em 0; color: ${themeColors.blockquoteText}; background: ${themeColors.blockquoteBg}; border-radius: 0 8px 8px 0; font-style: italic;`;
        });
    }
    
    styleLists(container, themeColors) {
        const lists = container.querySelectorAll('ul, ol');
        lists.forEach(list => {
            list.style.cssText += `margin: 1em 0; padding-left: 2em; line-height: 1.8; color: ${themeColors.text};`;
        });
        
        const listItems = container.querySelectorAll('li');
        listItems.forEach(li => {
            li.style.cssText += `margin: 0.5em 0; color: ${themeColors.text};`;
        });
    }
    
    styleTables(container, themeColors) {
        const tables = container.querySelectorAll('table');
        tables.forEach(table => {
            table.style.cssText += 'width: 100%; border-collapse: collapse; margin: 1em 0; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);';
        });
        
        const ths = container.querySelectorAll('th');
        ths.forEach(th => {
            th.style.cssText += `padding: 12px; text-align: left; border-bottom: 1px solid #ddd; background: linear-gradient(45deg, ${themeColors.primary}, ${themeColors.secondary}); color: white; font-weight: 600;`;
        });
        
        const tds = container.querySelectorAll('td');
        tds.forEach(td => {
            td.style.cssText += `padding: 12px; text-align: left; border-bottom: 1px solid #ddd; color: ${themeColors.text};`;
        });
        
        const trs = container.querySelectorAll('tr:not(:first-child)');
        trs.forEach(tr => {
            tr.style.cssText += 'transition: background-color 0.3s;';
            tr.addEventListener('mouseenter', () => {
                tr.style.backgroundColor = themeColors.codeBg;
            });
            tr.addEventListener('mouseleave', () => {
                tr.style.backgroundColor = '';
            });
        });
    }
    
    styleLinks(container, themeColors) {
        const links = container.querySelectorAll('a');
        links.forEach(link => {
            link.style.cssText += `color: ${themeColors.primary}; text-decoration: none; border-bottom: 1px solid ${themeColors.primary}; transition: all 0.3s;`;
        });
    }
    
    async copyMarkdown() {
        try {
            const markdownContent = this.editor.value;
            
            if (navigator.clipboard && navigator.clipboard.writeText) {
                await navigator.clipboard.writeText(markdownContent);
                this.showMessage('✅ 已复制Markdown格式！', 'success');
            } else {
                // 降级方法
                this.copyTextToClipboard(markdownContent);
                this.showMessage('✅ 已复制Markdown格式！', 'success');
            }
        } catch (error) {
            console.error('复制Markdown失败:', error);
            this.showMessage('❌ 复制失败，请手动选择内容复制', 'error');
        }
    }
    
    async copyPlainText() {
        try {
            const plainText = this.generatePlainText();
            
            if (navigator.clipboard && navigator.clipboard.writeText) {
                await navigator.clipboard.writeText(plainText);
                this.showMessage('✅ 已复制纯文本格式！', 'success');
            } else {
                // 降级方法
                this.copyTextToClipboard(plainText);
                this.showMessage('✅ 已复制纯文本格式！', 'success');
            }
        } catch (error) {
            console.error('复制纯文本失败:', error);
            this.showMessage('❌ 复制失败，请手动选择内容复制', 'error');
        }
    }
    
    copyTextToClipboard(text) {
        // 传统的文本复制方法
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-9999px';
        textArea.style.top = '-9999px';
        document.body.appendChild(textArea);
        
        try {
            textArea.focus();
            textArea.select();
            document.execCommand('copy');
        } finally {
            document.body.removeChild(textArea);
        }
    }
    
    clearEditor() {
        // 检查编辑器是否存在
        if (!this.editor) {
            console.error('编辑器元素未找到');
            this.showMessage('❌ 编辑器元素未找到', 'error');
            return;
        }
        
        // 如果编辑器已经为空，直接提示
        if (!this.editor.value.trim()) {
            this.showMessage('📝 编辑器已经是空的', 'info');
            return;
        }
        
        try {
            // 使用confirm确认清空
            const shouldClear = confirm('确定要清空编辑器内容吗？');
            if (shouldClear) {
                this.editor.value = '';
                this.updatePreview();
                this.showMessage('🗑️ 编辑器已清空', 'success');
            }
        } catch (error) {
            // 如果confirm失败，直接清空（可能在某些环境下confirm被阻止）
            console.warn('confirm对话框被阻止，直接清空:', error);
            this.editor.value = '';
            this.updatePreview();
            this.showMessage('🗑️ 编辑器已清空', 'success');
        }
    }
    
    async pasteFromClipboard() {
        try {
            const text = await navigator.clipboard.readText();
            this.editor.value = text;
            this.updatePreview();
            this.showMessage('📋 已粘贴剪贴板内容', 'success');
        } catch (error) {
            console.error('粘贴失败:', error);
            this.showMessage('❌ 粘贴失败，请手动粘贴内容', 'error');
        }
    }
    
    showMessage(message, type = 'info') {
        // 创建消息提示
        const messageDiv = document.createElement('div');
        messageDiv.textContent = message;
        messageDiv.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 8px;
            color: white;
            font-weight: 500;
            z-index: 1000;
            animation: slideIn 0.3s ease;
        `;
        
        // 根据类型设置颜色
        switch (type) {
            case 'success':
                messageDiv.style.background = 'linear-gradient(45deg, #28a745, #20c997)';
                break;
            case 'error':
                messageDiv.style.background = 'linear-gradient(45deg, #dc3545, #e74c3c)';
                break;
            case 'info':
            default:
                messageDiv.style.background = 'linear-gradient(45deg, #667eea, #764ba2)';
                break;
        }
        
        document.body.appendChild(messageDiv);
        
        // 3秒后自动移除
        setTimeout(() => {
            if (messageDiv.parentNode) {
                messageDiv.style.animation = 'slideOut 0.3s ease';
                setTimeout(() => {
                    document.body.removeChild(messageDiv);
                }, 300);
            }
        }, 3000);
    }
}

// 添加动画样式
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes slideOut {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(100%);
            opacity: 0;
        }
    }
`;
document.head.appendChild(style);

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    new LarkToMarkdown();
});

// 导出类供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = LarkToMarkdown;
}